//
//  TLNetworkTool.swift
//  TLSinaWeiBo
//
//  Created by 谭亮 on 16/5/14.
//  Copyright © 2016年 tanliang. All rights reserved.
//

import UIKit
import AFNetworking

//:->请求方法枚举
enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class TLNetworkTool: NSObject {
    //:单例
    static let sharedInstance: TLNetworkTool = TLNetworkTool()
    
    //:属性AFHttpSessionManager 
    //https://api.weibo.com/oauth2/access_token
    //https://api.weibo.com/2/statuses/home_timeline.json
    
    private let afnManager: AFHTTPSessionManager = {
    let afn = AFHTTPSessionManager(baseURL: NSURL(string: "http://api.weibo.com/2"))
        //:->给响应的序列化器多添加支持的类型
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return afn
    }()
    
        /*
    func requestGET(URLString: String, parameters:AnyObject?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?,failure: ((NSURLSessionDataTask?, NSError) -> Void)?) {
        afnManager.GET(URLString, parameters: parameters, success: success, failure: failure)
    }*/
    
    /*func requestGET(URLString: String, parameters: AnyObject?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?) {
        afnManager.GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
    }
    
    func requestPOST(URLString: String, parameters: AnyObject?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?) {
        afnManager.POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
    }*/
    
    
    //如果直接使用AFN的GET和POST方法,如果AFN改变了方法名或参数改变了,那项目中直接使用AFN,GET和POST的地方都需要改变
    //:自己封装GET 和 POST方法 ,项目中要使用GET和POST就用我们封装好的,到时如果AFN改变了方法名或参数,只需要改变我们封装好的方法
    
    //:封装AFN的GET和POST 通过参数来确定使用GET还是POST
    func request(method: RequestMethod, URLString: String, parameters: AnyObject?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?) {
        // GET和POST需要的参数我们这个方法里面不能确定,只有调用的人传递进来
        if method == RequestMethod.GET {
            afnManager.GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            afnManager.POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}

